<?php

require_once 'UserGroup.php';

/**
 *  zend db table
 */
class Application_Model_DbTable_UserGroups extends Zend_Db_Table_Abstract
{
    protected $_name = 'ap_user_group';
}


/**
 *  
 */
class UserGroups extends BaseMapper
{
    protected $_modelName   = 'UserGroup';
    protected $_dbTableName = 'Application_Model_DbTable_UserGroups';

    /* ================================================================================
        access database
    ================================================================================ */

    /**
     *  add UserGroup
     */
    public function addUserGroup( $model )
    {
        return $this->_save( $model, 'add' );
    }

    /**
     *  update UserGroup
     */
    public function updateUserGroup( $model )
    {
        return $this->_save( $model, 'update' );
    }

    /**
     *  get UserGroup
     */
    public function getUserGroup( $id, $status=UserGroup::STATUS_ALL )
    {
        $model = $this->_find($id);
        if( UserGroup::STATUS_ALL !== $status AND $model->getStatus() !== $status ) {
            return false;
        }
        return $model;
    }

    /**
     *  find many UserGroup
     */
    public function findUserGroups( $page=1, $rowCount=BaseMapper::DEFAULT_ROW_COUNT ) 
    {
        $opt = Array(
            '_orderBy'   => ' user_id DESC ',
            '_page'      => $page,
            '_rowCount'  => $rowCount,
        );
        return $this->_getByQuery($opt);
    }

    /**
     *  get UserGroup count
     */
    public function getCountByUserGroups() 
    {
        $opt = Array();
        return $this->_getByQuery($opt,true);
    }

    /**
     *  get UserGroup query
     */
    protected function _getByQuery( $opt, $isGetTotal=false )
    {
        $this->_checkOption($opt);
        $opt += Array(
            'userId'               => (isset($opt['userId'])               ? (int) ($opt['userId'])               : NULL ),
            'serviceKey'           => (isset($opt['serviceKey'])           ?       ($opt['serviceKey'])           : NULL ),
            'serviceId'            => (isset($opt['serviceId'])            ? (int) ($opt['serviceId'])            : NULL ),

            '_orderBy'             => (isset($opt['_orderBy'])             ?       ($opt['_orderBy'])             : ' id DESC ' ),
            '_page'                => (isset($opt['_page'])                ? (int) ($opt['_page'])                : 1 ),
            '_rowCount'            => (isset($opt['_rowCount'])            ? (int) ($opt['_rowCount'])            : BaseMapper::DEFAULT_ROW_COUNT ),
        );

        if( isset($opt['_page']) && $opt['_page']<=1 ) {
            $opt['_page'] = 1;
        }

        $where = Array();
        if(isset( $opt['userId']              )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' user_id = ? '             , $opt['userId']               );  }
        if(isset( $opt['serviceKey']          )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' service_key = ? '         , $opt['serviceKey']           );  }
        if(isset( $opt['serviceId']           )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' service_id = ? '          , $opt['serviceId']            );  }

        $where = join(' AND ',$where);
        if(!$where) {
            $where = null;
        }

        // get total
        if( $isGetTotal ) {
            $select = $this->getDb()->select();
            $select->from( $this->getDb(), Array('COUNT(*) AS total') );
            if($where) {
                $select->where( $where );
            }
            $rows = $this->getDb()->fetchRow($select);
            $row = $rows->toArray();
            return (int) $row['total'];
        }

        //
        //echo join(' AND ',$where); exit;

        //
        if( NULL === $opt['_page'] ) {
            $rowset = $this->getDb()->fetchAll($where, $opt['_orderBy']);
        }
        else {
            $offset = ($opt['_page']-1) * $opt['_rowCount'];
            $rowset = $this->getDb()->fetchAll($where, $opt['_orderBy'], $opt['_rowCount'], $offset );
        }

        if( !$rowset ) {
            return NULL;
        }

        $models = Array();
        foreach( $rowset as $row ) {
            $models[] = $this->mapRow( $row->toArray() );
        }
        return $models;

    }

    /* ================================================================================
        about model object
    ================================================================================ */

    /**
     *  set mapRow by pure database record
     */
    public function mapRow($row)
    {
        $model = $this->getModel();
        $model->setUserId               ( $row['user_id']              );
        $model->setServiceKey           ( $row['service_key']          );
        $model->setServiceId            ( $row['service_id']           );
        return $model;
    }

}

